import React, {useState} from 'react';
import {Plus, ExternalLink, Trash2, FolderOpen} from 'lucide-react';
import {Button, IconButton} from '@/components/ui/Button';
import {useCollectionsData} from '@/hooks/data';
import {useDeleteCollection} from '@/hooks/api/useCollections';
import {useActiveSpaceStore} from '@/stores/activeSpace';
import {useToast} from '@/hooks/ui';
import {saveCurrentWindowAsCollection, openCollectionSmart} from '@/services';
import {formatDate} from '@/lib/utils';
import type {SpaceCollection} from '@/types';
import {ScrollContainer} from '@/components/ui/ScrollContainer';

// 集合项组件
interface CollectionItemProps {
    collection: SpaceCollection;
}

// 单个集合项组件
const CollectionItem: React.FC<CollectionItemProps> = ({collection}) => {
    const deleteCollectionMutation = useDeleteCollection();
    const toast = useToast();

    // 打开集合
    const handleOpen = async () => {
        try {
            await openCollectionSmart(collection.collectionId);
        } catch (error) {
            toast.error('打开失败，请重试');
        }
    };

    // 删除集合
    const handleDelete = async () => {
        try {
            await deleteCollectionMutation.mutateAsync({
                collectionId: collection.collectionId,
                spaceId: collection.spaceId,
            });
            toast.success('集合已删除');
        } catch (error) {
            toast.error('删除失败，请重试');
        }
    };

    return (
        <div className="collection-item p-3 border-b border-gray-100 hover:bg-gray-50">
            {/* 集合头部信息 */}
            <div className="flex items-start justify-between mb-2">
                <div className="flex-1 min-w-0">
                    {/* 集合名称 */}
                    <h4 className="font-medium text-gray-900 text-sm truncate mb-1">
                        {collection.collection.name}
                    </h4>

                    {/* 集合统计信息 */}
                    <div className="flex items-center gap-3 text-xs text-gray-500">
            <span className="flex items-center gap-1">
              <FolderOpen size={12}/>
                {collection.tabs.length} 个标签
            </span>
                        <span>
              {formatDate(collection.collection.createdAt)}
            </span>
                    </div>
                </div>

                {/* 操作按钮 */}
                <div className="flex items-center gap-1 ml-2">
                    <IconButton
                        variant="ghost"
                        size="sm"
                        onClick={handleOpen}
                        className="text-blue-600 hover:text-blue-700 hover:bg-blue-50"
                        icon={<ExternalLink size={14}/>}
                        aria-label="打开集合"
                    />

                    <IconButton
                        variant="ghost"
                        size="sm"
                        onClick={handleDelete}
                        className="text-gray-400 hover:text-red-600 hover:bg-red-50"
                        icon={<Trash2 size={14}/>}
                        aria-label="删除集合"
                    />
                </div>
            </div>
        </div>
    );
};

// Popup页面组件
// 复刻原有功能：保存当前窗口、显示集合列表、快速操作
export const Popup: React.FC = () => {
    // 状态管理
    const [collectionName, setCollectionName] = useState('');
    const [isSaving, setIsSaving] = useState(false);

    // 获取当前活跃空间
    const activeSpaceId = useActiveSpaceStore((state) => state.activeSpaceId);

    // 使用新的数据 hook
    const { collections, isLoading } = useCollectionsData(activeSpaceId);

    const toast = useToast();

    // 获取集合列表（按时间倒序）
    const collectionsList = collections;

    // 保存当前窗口为新集合
    const handleSave = async () => {
        // 检查是否有活跃空间
        if (!activeSpaceId) {
            toast.error('未选择工作空间');
            return;
        }

        setIsSaving(true);
        try {
            // 使用更新后的保存逻辑，传入当前活跃空间ID
            saveCurrentWindowAsCollection(activeSpaceId, collectionName.trim(), '弹窗于').then(r => {
                if (r.savedTabIds.length === 0) {
                    toast.info('当前窗口没有可保存的标签页');
                    return;
                }
                // 清空输入框
                setCollectionName('');
                toast.success('已保存当前窗口');
            });
        } catch (error) {
            console.error('保存集合失败:', error);
            toast.error('保存失败，请重试');
        } finally {
            setIsSaving(false);
        }
    };

    return (
        <div className="popup-container w-80 max-h-128 flex flex-col bg-white">
            {/* 头部：保存新集合 */}
            <div className="p-4 border-b border-gray-200">
                <h2 className="text-lg font-semibold text-gray-900 mb-3">
                    Tab Lite
                </h2>

                {/* 保存表单 */}
                <div className="space-y-3">
                    <input
                        type="text"
                        id="collectionName"
                        value={collectionName}
                        onChange={(e) => setCollectionName(e.target.value)}
                        placeholder="集合名称（可选）"
                        className="input w-full px-3 py-2 text-sm"
                        disabled={isSaving}
                    />

                    <Button
                        id="saveBtn"
                        variant="primary"
                        size="sm"
                        onClick={handleSave}
                        loading={isSaving}
                        leftIcon={<Plus size={14}/>}
                        className="w-full"
                        disabled={isSaving}
                    >
                        {isSaving ? '保存中...' : '保存当前窗口'}
                    </Button>
                </div>
            </div>

            {/* 集合列表 */}
            <div className="flex-1 min-h-0 overflow-hidden">
                {isLoading ? (
                    /* 加载状态 */
                    <div className="flex items-center justify-center py-8">
                        <div className="text-center text-gray-500">
                            <div className="animate-pulse">加载中...</div>
                        </div>
                    </div>
                ) : collectionsList.length === 0 ? (
                    /* 空状态 */
                    <div className="flex items-center justify-center py-8">
                        <div className="text-center text-gray-500">
                            <FolderOpen size={32} className="mx-auto mb-2 opacity-50"/>
                            <p className="text-sm">还没有保存的集合</p>
                        </div>
                    </div>
                ) : (
                    /* 集合列表（统一滚动条样式，通过 Tailwind 控制高度） */
                    <ScrollContainer className="h-64" padRightForScrollbar={false}>
                        <div id="list" className="pb-3">
                            {collectionsList.map((collection) => (
                                <CollectionItem key={collection.collectionId} collection={collection}/>
                            ))}
                        </div>
                    </ScrollContainer>
                )}
            </div>

            {/* 底部信息 */}
            {collectionsList.length > 0 && (
                <div className="px-4 py-2 border-t border-gray-100 bg-gray-50">
                    <p className="text-xs text-gray-500 text-center">
                        共 {collectionsList.length} 个集合
                    </p>
                </div>
            )}
        </div>
    );
};
